package com.bea.ftd.mapping.message;

import com.bea.ftd.common.entity.MsgInConf;
import com.thoughtworks.xstream.XStream;
import com.thoughtworks.xstream.io.xml.DomDriver;

import java.io.IOException;

public class XmlUtils {
    /**
     * XML内容转化为对象
     * @param content
     * @param valueType
     * @param <T>
     * @return
     */
    public static <T> T readValue(String content, Class<T> valueType) {
        XStream xstream = new XStream(new DomDriver());
        xstream.processAnnotations(valueType);
        return (T) xstream.fromXML(content);
    }
    /**
     * 对象转化为XML内容
     * @param t
     * @param <T>
     * @return
     * @throws IOException
     */
    public static  <T> String writeValueAsString(T t) throws IOException {
        XStream xstream = new XStream(new DomDriver("utf8"));
        xstream.processAnnotations(t.getClass());// 识别obj类中的注解
        // 以格式化的方式输出XML
        return xstream.toXML(t);
    }

    public static void main(String[] args) throws IOException {
        String xmlString ="<com.bea.ftd.common.entity.MsgInConf> <apiId>321</apiId> <msgInType>xml</msgInType><paramName>red</paramName><paramNote>qwe</paramNote></com.bea.ftd.common.entity.MsgInConf>";
        String rootClassPath = Thread.currentThread().getContextClassLoader ().getResource("").getPath();

        System.out.println(xmlString);
        MsgInConf msgInConf = readValue(xmlString,MsgInConf.class);
        System.out.println(msgInConf);
    }
}
